/*
 * DiscoverySearchAccuratePresenter.java
 * business
 *
 * Created by chentao on 2017/4/21.
 *
 * Copyright (c) 2017年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.ui.main.discovery.searchaccurate;

import android.text.TextUtils;

import com.yidiandao.business.R;
import com.yidiandao.business.data.model.IDiscoverySearchModel;
import com.yidiandao.business.data.recyclertype.AccurateContent;
import com.yidiandao.business.data.recyclertype.Article;
import com.yidiandao.business.ui.widget.view.SuperLoadingLayout;
import com.yidiandao.business.utils.UIUtils;

import java.util.List;

/**
 * Presenter
 */
public class DiscoverySearchAccuratePresenter implements DiscoverySearchAccurateContract.Presenter {

    private DiscoverySearchAccurateContract.View mSearchAccurateView;

    private AccurateContent mAccurateContent;

    private IDiscoverySearchModel mSearchModel;

    public DiscoverySearchAccuratePresenter(DiscoverySearchAccurateContract.View view, AccurateContent accurateContent,
                                            IDiscoverySearchModel searchModel) {
        mSearchAccurateView = view;
        mAccurateContent = accurateContent;
        mSearchModel = searchModel;

        mSearchAccurateView.setPresenter(this);
    }

    @Override
    public void start() {
        if (!TextUtils.isEmpty(mAccurateContent.getKeyword())) {
            search(mAccurateContent.getKeyword(), true);
            mSearchAccurateView.setTitleHint(UIUtils.getString(R.string.search_accurate, mAccurateContent.getKeyword()));
        } else {
            mSearchAccurateView.setTitleHint(UIUtils.getString(R.string.search_accurate, mAccurateContent.getName()));
            mSearchAccurateView.refreshContent(SuperLoadingLayout.STATE_NONE);
        }
    }

    @Override
    public void search(String keyword, final boolean isRefreshing) {

        mSearchModel.searchAccurate(mSearchAccurateView.getPagerTag(), isRefreshing,
                mAccurateContent.getId(), keyword, new IDiscoverySearchModel.OnLoadResultListener<List<Article>>() {
                    @Override
                    public void onSuccess(List<Article> articles, boolean emptyData, boolean hasMore) {
                        if (isRefreshing) {
                            mSearchAccurateView.refreshContent(mSearchAccurateView.checkResultObject(articles));
                        }
                        mSearchAccurateView.setItems(articles);
                        mSearchAccurateView.loadMoreFinish(emptyData, hasMore);
                    }

                    @Override
                    public void onFailed() {
                        if (isRefreshing) {
                            mSearchAccurateView.refreshContent(SuperLoadingLayout.STATE_ERROR);
                        } else {
                            mSearchAccurateView.loadMoreError();
                        }
                    }
                });
    }
}
